package com.example.lycdays.ui.profile;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.cardview.widget.CardView;
import androidx.fragment.app.Fragment;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.example.lycdays.BaseApplication;
import com.example.lycdays.R;
import com.example.lycdays.data.bean.Event;
import com.example.lycdays.data.bean.Result;
import com.example.lycdays.data.bean.User;
import com.example.lycdays.data.repositiory.EventDataBase;
import com.example.lycdays.ui.detail.DetailActivity;
import com.example.lycdays.ui.login.LoginActivity;
import com.google.gson.Gson;

import org.litepal.LitePal;

import java.util.HashMap;
import java.util.List;

import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * A simple {@link Fragment} subclass.
 */
public class ProfileFragment extends Fragment {

    private static final String TAG = "myTag";
    private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
    private String URL;

    Result result = null;
    List<Event> events = null;
    Button button;
    CardView cardView1, cardView2;
    TextView textViewName;

    public ProfileFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_profile, container, false);
        return view;
    }


    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        button = getView().findViewById(R.id.buttonLogin);
        cardView1 = getView().findViewById(R.id.cardView_1);
        cardView2 = getView().findViewById(R.id.cardview_2);
        textViewName = getView().findViewById(R.id.textView_username);
        URL = getString(R.string.URL);

        User user = LitePal.findFirst(User.class);
        if (user == null) {
            textViewName.setVisibility(View.GONE);
            button.setVisibility(View.VISIBLE);

        } else {
            button.setVisibility(View.GONE);
            textViewName.setVisibility(View.VISIBLE);
            textViewName.setText(user.getUserName());
        }

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity() , LoginActivity.class);
                startActivity(intent);
            }
        });

        textViewName.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //    通过AlertDialog.Builder这个类来实例化我们的一个AlertDialog的对象
                AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
                //    设置Title的图标
                builder.setIcon(R.drawable.ic_error_blue_24dp);
                //    设置Title的内容
                builder.setTitle("注销");
                //    设置Content来显示一个信息
                builder.setMessage("确定退出登录吗？");
                //    设置一个PositiveButton
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener()
                {
                    @Override
                    public void onClick(DialogInterface dialog, int which)
                    {
                        LitePal.deleteAll(User.class);
                        BaseApplication.setIsRegister(false);
                        textViewName.setVisibility(View.GONE);
                        button.setVisibility(View.VISIBLE);

                        Toast.makeText(getContext(), "注销成功", Toast.LENGTH_SHORT).show();
                    }
                });
                //    设置一个NegativeButton
                builder.setNegativeButton("取消", new DialogInterface.OnClickListener()
                {
                    @Override
                    public void onClick(DialogInterface dialog, int which)
                    {
                        //Toast.makeText(DetailActivity.this, "negative: " + which, Toast.LENGTH_SHORT).show();

                    }
                });
                //    显示出该对话框
                builder.show();
            }
        });


        cardView1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!BaseApplication.isIsRegister())
                {
                    Toast.makeText(getContext(), "请先登录或注册", Toast.LENGTH_SHORT).show();
                } else {
                    Gson gson = new Gson();
                    List<Event> events = EventDataBase.findAllEvents();
                    for (Event event: events) {
                        event.setUserName(LitePal.findFirst(User.class).getUserName());
                        backUpWithOkhttp(gson.toJson(event));
                    }
                    Toast.makeText(getContext(), "备份成功", Toast.LENGTH_SHORT).show();
                }
            }
        });
        cardView2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!BaseApplication.isIsRegister())
                {
                    Toast.makeText(BaseApplication.getContext(), "请先登录或注册", Toast.LENGTH_SHORT).show();
                } else {
                    Gson gson = new Gson();
                    User user = LitePal.findFirst(User.class);
                    reStoreWithOkhttp(gson.toJson(user));



                    Toast.makeText(getContext(), "恢复成功", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    private void reStoreWithOkhttp(final String param) {

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Log.d(TAG, URL + "/event/find_all");
                    OkHttpClient client = new OkHttpClient();
                    RequestBody requestBody = RequestBody.create(JSON, param);
                    Request request = new Request.Builder()
                            .post(requestBody)
                            .url("http://" + URL + "/event/find_all")
                            .build();

                    Response response = client.newCall(request).execute();
                    String responseData = response.body().string();

                    //
                    handleRestoreResult(responseData);

//                    for (Event event : events) {
//                        // 如果本地没有该事件才插入
//                        Event eventExist = EventDataBase.findEventByCreateTime(event.getCreateTime());
//                        if (eventExist == null) {
//                            EventDataBase.insertEvent(event);
//                        }
//                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();

    }

    private void backUpWithOkhttp(final String param) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Log.d(TAG, URL + "/event/insert");
                    OkHttpClient client = new OkHttpClient();
                    RequestBody requestBody = RequestBody.create(JSON, param);
                    Request request = new Request.Builder()
                            .post(requestBody)
                            .url("http://" + URL + "/event/insert")
                            .build();

                    Response response = client.newCall(request).execute();
                    String responseData = response.body().string();
                    Log.d(TAG, "data: " + responseData);

                    handleBackUpResult(responseData);

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private void handleBackUpResult(final String responseData) {
        result = null;
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                parseJSONWithGSON(responseData);
            }
        });
    }

    private void handleRestoreResult(final String responseData) {
        result = null;
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                parseJSONWithGSON(responseData);
            }
        });
    }


    private void parseJSONWithGSON(String jsonData) {
        Gson gson = new Gson();
        result = gson.fromJson(jsonData, Result.class);
        Log.d(TAG, "data: " + result.getMsg());
        Log.d(TAG, "data: " + result.getDetail());

        if (result.getDetail() != null)
        {

            List<Result.DetailBean> detailBeans = result.getDetail();
            for(Result.DetailBean detailBean : detailBeans) {

                // 本地没有该事件写入
                Event eventExist = EventDataBase.findEventByCreateTime(detailBean.getCreateTime());
                if (eventExist == null) {
                    Event event = new Event();
                    event.setEventName(detailBean.getName());
                    event.setEventDate(detailBean.getDate());
                    event.setCreateTime(detailBean.getCreateTime());
                    event.setEventNotes(detailBean.getNote());
                    EventDataBase.insertEvent(event);
                }
            }
        }

    }



    @Override
    public void onResume() {
        super.onResume();

        User user = LitePal.findFirst(User.class);
        if (user == null) {
            textViewName.setVisibility(View.GONE);
            button.setVisibility(View.VISIBLE);
            button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(getActivity() , LoginActivity.class);
                    startActivity(intent);
                }
            });
        } else {
            button.setVisibility(View.GONE);
            textViewName.setVisibility(View.VISIBLE);
            textViewName.setText(user.getUserName());
        }

    }
}
